﻿using Bridge.Shared.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Microsoft.AspNetCore.DataProtection;

namespace Bridge.Shared.Extensions
{
    public static class RedisExtension
    {
        public static void UseRedis(this IServiceCollection service, IConfiguration configuration)
        {
            service.Configure<RedisConfiguration>(configuration.GetSection("Redis"));

            var redisConfiguration = configuration.GetSection("Redis").Get<RedisConfiguration>();
           
            //拼接链接字符串
            var connectStr = $"{redisConfiguration.Configuration},defaultDatabase={redisConfiguration.DatabaseId}";
            if (!string.IsNullOrEmpty(redisConfiguration.RedisDataProtectionKey))
            {
                connectStr += ("," + redisConfiguration.RedisDataProtectionKey);
            }

            service.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = connectStr;
            });

            var redis = ConnectionMultiplexer.Connect(connectStr);
            service.AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

            service.AddTransient<IRedisConnectionWrapper, RedisConnectionWrapper>();
            service.AddTransient<ICacheManager, RedisManager>();
        }
    }
}
